package interceptcrossing.ui;

import interceptcrossing.Abscissa;
import interceptcrossing.Intercept;
import interceptcrossing.Intersection;

import javax.swing.*;
import java.awt.*;
import java.util.Collection;

/**
 * @author: Igor Botyan
 * @date: May 7, 2010
 */
public class AbscissaLinePanel extends JPanel {

	private DebugWindowDirector windowDirector;
	private InterceptPaintUtils paintUtils;
	private Abscissa currentAbscissa;

	public AbscissaLinePanel(DebugWindowDirector windowDirector) {
		if (windowDirector == null) {
			throw new NullPointerException("Debug window director cannot be null");
		}

		this.windowDirector = windowDirector;
		this.paintUtils = new InterceptPaintUtils(this);
		this.paintUtils.recalculateAbscissaBound(this.windowDirector.getIntercepts());

		this.initActions();
	}

	private void initActions() {
		this.windowDirector.addListener(new DebugWindowDirector.Listener() {

			public void currentAbscissaChanged(Abscissa abscissa, Collection<Intercept> aboveIntercepts,
			                                   Collection<Intercept> underIntercepts) {
				AbscissaLinePanel.this.currentAbscissa = abscissa;
				AbscissaLinePanel.this.repaint();
			}
		});
	}

	@Override
	protected void paintBorder(Graphics g) {
		super.paintBorder(g);

		Graphics2D g2d = (Graphics2D) g;

		this.paintUtils.paintBackground(g2d);
		this.paintUtils.paintAbscissaAxis(g2d);

		int height = this.getHeight() / 2;

		for (Intercept intercept : this.windowDirector.getIntercepts()) {
			Point begin = this.paintUtils.toComponentCoords(intercept.begin());
			Point end = this.paintUtils.toComponentCoords(intercept.end());

			this.paintUtils.paintInterceptBoundPoint(g2d, new Point((int) begin.getX(), height));
			this.paintUtils.paintInterceptBoundPoint(g2d, new Point((int) end.getX(), height));
		}

		for (Intersection intersection : this.windowDirector.getIntersections()) {
			Point begin = this.paintUtils.toComponentCoords(intersection.point());
			this.paintUtils.paintIntersectionPoint(g2d, new Point((int) begin.getX(), height));
		}

		if (this.currentAbscissa != null) {
			this.paintUtils.paintSweptLine(g2d, this.currentAbscissa.x);
		}
	}
}
